package com.etlmaster.executor.steps.control;

import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.etlmaster.executor.Job;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.steps.control.ControlStep;

/**
 * 条件判断控制
 * @author MeiKefu
 * @date 2014-8-4
 */
@StepInstruction("if")
public class ConditionalStep extends ControlStep {
	
	
	private ConditionalStepMeta meta;

	public ConditionalStep(StepMeta meta) {
		super(meta);
		this.meta = (ConditionalStepMeta)meta;
	}

	/**
	 * 获取判断成功的步骤
	 * @return
	 */
	public StepMeta getSuccessStep(Job job) {
		//判断是否是否正确
		ScriptEngineManager sem = new ScriptEngineManager();
		ScriptEngine engine = null;
	    try{
	    	engine = sem.getEngineByName("nashorn");
	    	if(engine==null){
	    		meta.log("DEBUG","创建nashorn引擎失败，未使用Jdk 8，使用默认Rhino引擎");
		    	engine = sem.getEngineByName("JavaScript");
	    	}
	    }catch(Exception e){
	    	meta.log("DEBUG","创建nashorn引擎失败，不是使用Jdk 8使用默认Rhino引擎，{}",e.getMessage());
	    	engine = sem.getEngineByName("JavaScript");
	    }
		String successStepId = null;
		
		String elseStepId = null;
		
		for (int i = 0; i < meta.getStatements().size(); i++) {
			Map<String,String> statement = meta.getStatements().get(i);
			String expression = meta.variableSubstitution(statement.get("expression"));
			
			if("else".equals(expression)){//为esle先跳过，如果没有满足的就走到elseStep
				elseStepId = statement.get("stepId");
				continue;
			}
			
			StringBuilder script = new StringBuilder("(function(){return ");
			script.append(expression).append(" ;})()");
			
			boolean result = false;
			try {
				result = (Boolean)engine.eval(script.toString());
				meta.log("DEBUG","校验结果：{},脚本为[{}]", String.valueOf(result), script.toString());
			} catch (ScriptException e) {
				meta.log("ERROR","逻辑判断表达式运行失败[{}]",expression);
			}
			if(result){
				successStepId = statement.get("stepId");

				break;
			}
		}
		
		if(successStepId==null ){//没有条件成功，但是有else的
			if(elseStepId!=null){
				successStepId = elseStepId;
			}else{//TODO 没有任何成功的下一步骤，应该走到条件判断的框体外
				meta.log("WARN","没有任何成功的下一步骤");
			}
		}
		
	    StepMeta result = null;
	    if(successStepId!=null){
	    	List<StepMeta> stepMetas = job.getNextStepMetas(meta.getId());
			for (int i = 0; i < stepMetas.size(); i++) {
				StepMeta stepMeta = stepMetas.get(i);
				if(successStepId.equalsIgnoreCase(stepMeta.getId())){
					result = stepMeta;
					break;
				}
			}
	    }
		return result;
	}

}
